package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

@Configuration //声明当前配置类为核心配置类
@ComponentScan("com.itheima") //开启组件扫描
@PropertySource("druid.properties") //加载外部资源配置文件
@Import(ConfigMapper.class)  //加载子配置类
public class SpringConfig {

    @Value("${jdbc.driverClassName}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    //声明一个方法获取数据源对象
    @Bean
    public DataSource getDataSource() {
        DruidDataSource source = new DruidDataSource();
        source.setDriverClassName(driver);
        source.setUrl(url);
        source.setUsername(username);
        source.setPassword(password);
        return source;
    }

    @Bean
    public SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        //source 注入数据源
        sqlSessionFactory.setDataSource(dataSource);
        //类型起别名
        sqlSessionFactory.setTypeAliasesPackage("com.itheima.pojo");
        return sqlSessionFactory;
    }

}
